package com.binguo.api.service;

import com.alibaba.fastjson.JSONObject;
import com.binguo.api.baidu.BaiduRecUtil;
import com.binguo.api.response.api.BaseChargeResp;
import com.binguo.api.response.api.BaseUserInfo;
import com.binguo.api.response.renshoutang.consume.ConsumeParam;
import com.binguo.api.response.renshoutang.consume.ConsumeProduct;
import com.binguo.api.response.renshoutang.consume.ConsumeResp;
import com.binguo.api.response.renshoutang.productlist.Data;
import com.binguo.api.response.renshoutang.productlist.Foodlist;
import com.binguo.api.response.renshoutang.productlist.GetProductListResp;
import com.binguo.api.schedule.DataLoadService;
import com.binguo.api.service.api.ShopApiInterface;
import com.binguo.common.enums.CardType;
import com.binguo.common.paymodel.MD5Util;
import com.binguo.common.paymodel.ThreadManager;
import com.binguo.common.util.FileDownloader;
import com.binguo.common.util.JsonUtil;
import com.binguo.common.util.PriceUtil;
import com.binguo.model.api.dto.OrderDTO;
import com.binguo.model.api.dto.OrderItemDTO;
import com.binguo.model.mapper.*;
import com.binguo.model.model.*;
import com.binguo.model.repository.CustomerRepository;
import com.binguo.model.repository.ProductCategoryRepository;
import com.binguo.model.repository.ProductRepository;
import com.binguo.thirdPay.ruijingPay.RuiJingPayForm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import tk.mybatis.mapper.entity.Condition;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class RenShouTangService implements ShopApiInterface, InitializingBean {
    private static Logger logger = LoggerFactory.getLogger(RenShouTangService.class);

    private static String sitUserInfoRequestUrl = "https://prlyl.cn/ykt/api/ypCallApi/cardInfo.do";
    private static String sitConsumeRequestUrl = "https://prlyl.cn/ykt/api/ypCallApi/consume.do";
    private static String sitProductRequestUrl = "https://prlyl.cn/ykt/api/ypCallApi/getFoods.do";

    private static String appIdStatic = "yphq";
//    private static String branchIdStatic = "2";
    private static String branchIdStatic = "28";
    private static String passwordStatic = "0417d715ba22a924d9714a4c84514d80";


    /*private static String sitUserInfoRequestUrl = "https://nhs-sit.wilmar.cn/ykt/api/ypCallApi/cardInfo.do";
    private static String sitConsumeRequestUrl = "https://nhs-sit.wilmar.cn/ykt/api/ypCallApi/consume.do";
    private static String sitProductRequestUrl = "https://nhs-sit.wilmar.cn/ykt/api/ypCallApi/getFoods.do";
    private static String appIdStatic = "yp";
    private static String branchIdStatic = "106";
    private static String passwordStatic = "7e08c055060352fba32555e376b641aa";*/
    private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");

    private Integer shopId;
    private String shopName;

    @Resource
    private ShopMapper shopMapper;


    @Resource
    private BranchMapper branchMapper;

    @Resource
    private ProductRepository productRepository;

    @Resource
    private LogProductImgMapper logProductImgMapper;

    @Resource
    private LogProductImgCurMapper logProductImgCurMapper;
    @Resource
    private LogProductImgFromUserMapper logProductImgFromUserMapper;

    @Resource
    private LogShopBaiduImgDelMapper logShopBaiduImgDelMapper;

    @Resource
    private BaiduRecUtil baiduRecUtil;

    @Resource
    RedisLockService redisLockService;

    @Resource
    CustomerRepository customerRepository;

    @Resource
    PayCardMapper payCardMapper;

    @Resource
    CustomerExtendMapper customerExtendMapper;


    private HttpHeaders DEFAULT_JSON_HEADER_UTF8;

    public RenShouTangService() {


        DEFAULT_JSON_HEADER_UTF8 = new HttpHeaders();
        DEFAULT_JSON_HEADER_UTF8.setContentType(MediaType.APPLICATION_JSON_UTF8);
    }

    @Resource
    private ProductCategoryRepository productCategoryRepository;

    @Resource
    private ProductMapper productMapper;

    @Override
    public BaseChargeResp payPreHandler(OrderDTO orderDTO) {
        return null;
    }

    @Override
    public BaseChargeResp payPostHandler(OrderDTO orderDTO) {
        return null;
    }

    @Override
    public BaseUserInfo getUserInfo(String cardNo) {
        TreeMap<String, String> param = new TreeMap();
        param.put("appid", appIdStatic);
        param.put("cardNo", cardNo);
        param.put("nonceStr", UUID.randomUUID().toString().replaceAll("-", ""));
        param.put("password", passwordStatic);
        param.put("time", simpleDateFormat.format(new Date()));

        String sign = getSign(param);

        param.put("sign", sign);
        param.remove("password");

        String p = sitUserInfoRequestUrl + "?";
        for (Map.Entry<String, String> entry : param.entrySet()) {
            p += entry.getKey() + "=" + entry.getValue() + "&";
        }


        p = p.substring(0, p.length() - 1);
        logger.info(p);

        ResponseEntity<String> responseEntity =
                new RestTemplate().getForEntity(p, String.class, new HashMap<>());

        logger.info(responseEntity.getBody());

        try {
            Map map = JsonUtil.parse(responseEntity.getBody(), Map.class);
//            CardInfoResp cardInfoResp = JsonUtil.parse(responseEntity.getBody(), CardInfoResp.class);

            String code = (String)map.get("code");
            if (code.equals("0")) {
                BaseUserInfo baseUserInfo = new BaseUserInfo();
                Map data = (Map) map.get("data");
                int balance = (int) data.get("balance");
                String name = (String) data.get("name");
                baseUserInfo.setBalance(Long.valueOf(balance));
                baseUserInfo.setCardNo(cardNo);
                if (data.containsKey("phone")) {
                    String phone = (String) data.get("phone");
                    baseUserInfo.setPhone(phone);
                }
                baseUserInfo.setUsername(name);

                return baseUserInfo;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public BaseChargeResp cardPay(OrderDTO orderDTO) {

        ConsumeResp consumeResp = doPay(orderDTO, "card");

        if (consumeResp != null && consumeResp.getCode() == 0) {
            ThreadManager.executorService.execute(()->{
                BaseUserInfo baseUserInfo = getUserInfo(orderDTO.getCardNo());
                if (baseUserInfo != null) {
                    Condition condition = new Condition(PayCard.class);
                    condition.or().andEqualTo("shopid", shopId)
                                .andEqualTo("cardno", orderDTO.getCardNo())
                                .andEqualTo("deleted", false)
                    ;
                    List<PayCard> payCardList = payCardMapper.selectByCondition(condition);
                    if (payCardList != null && payCardList.size() > 0) {
                        logger.info("renshoutang card exist:{}", orderDTO.getCardNo());
                        PayCard dbPayCard = payCardList.get(0);
                        PayCard temp = new PayCard();
                        temp.setYktAccountbalance(baseUserInfo.getBalance());
                        temp.setId(dbPayCard.getId());

                        payCardMapper.updateByPrimaryKeySelective(temp);
                    }else {
                        logger.info("renshoutang card notexist:{}", orderDTO.getCardNo());
                        Customer customer = new Customer();
                        customer.setName(baseUserInfo.getUsername());
                        customer.setPhone(baseUserInfo.getPhone());
                        customer.setCreated(new Date());
                        customer.setUpdated(customer.getCreated());

                        customerRepository.save(customer);

                        CustomerExtend customerExtend = new CustomerExtend();
                        customerExtend.setIsAudit(1);
                        customerExtend.setShopId(shopId);
                        customerExtend.setCustomerId(customer.getId());
                        customerExtend.setUserStatus(1);
                        customerExtendMapper.insertSelective(customerExtend);

                        PayCard payCard = new PayCard();
                        payCard.setCardno(orderDTO.getCardNo());
                        payCard.setShopid(shopId);
                        payCard.setName(customer.getName() + "的一卡通");
                        payCard.setDeleted(false);
                        payCard.setCustomerid(customer.getId());
                        payCard.setIsmaster(true);
                        payCard.setCardtype(CardType.BINGUO_CARD.getCode().byteValue());
                        payCard.setCreated(new Date());
                        payCard.setUpdated(payCard.getCreated());
                        payCard.setYktAccountbalance(baseUserInfo.getBalance());
                        payCard.setBzAccountbalance(0l);
                        payCard.setWxAccountbalance(0l);
                        payCard.setAccountbalance(0l);
                        payCardMapper.insertSelective(payCard);
                    }
                }
            });
            return BaseChargeResp.genSuccessResult(consumeResp.getData().getBalance());
        }

        return BaseChargeResp.genFailResult(consumeResp.getMsg());
    }

    @Override
    public BaseChargeResp wxPay(OrderDTO orderDTO) {
        doPay(orderDTO, "wx");
        return null;
    }

    @Override
    public BaseChargeResp aliPay(OrderDTO orderDTO) {
        doPay(orderDTO, "ali");
        return null;
    }

    @Override
    public BaseChargeResp facePay(OrderDTO orderDTO) {
        return null;
    }

    @Override
    public BaseChargeResp cashPay(OrderDTO orderDTO) {
        doPay(orderDTO, "cash");
        return null;
    }


//    @Scheduled(cron="0 0 0/2 * * ?")
    @Scheduled(cron="0 0/3 * * * ?") //每隔十分钟执行
    @Override
    public BaseChargeResp getProductList() {
        logger.info("====renShouTangGetProductList===");
        String key = "renShouTangGetProductList";

        String uuid = UUID.randomUUID().toString();
        boolean lock = redisLockService.setLockOrder(key, 100000, uuid);
//        boolean lock = redisLockService.setLock(key, 100000, uuid);
        if (lock) {
            TreeMap<String, String> param = new TreeMap();
            param.put("appid", appIdStatic);
            param.put("nonceStr", UUID.randomUUID().toString().replaceAll("-", ""));
            param.put("password", passwordStatic);
            param.put("branchid", branchIdStatic);
            param.put("time", simpleDateFormat.format(new Date()));

            String sign = param.get("appid") +
                    param.get("password") + param.get("nonceStr") +
                    param.get("time") + param.get("branchid");

            logger.info(sign);
            sign = MD5Util.MD5Lower32(sign);

            param.put("sign", sign);
            param.remove("password");

            String p = sitProductRequestUrl + "?";
            for (Map.Entry<String, String> entry : param.entrySet()) {
                p += entry.getKey() + "=" + entry.getValue() + "&";
            }


            p = p.substring(0, p.length() - 1);
            logger.info(p);

            try {

                ResponseEntity<String> responseEntity =
                        new RestTemplate().getForEntity(p, String.class, new HashMap<>());

//                logger.info(responseEntity.getBody());
                GetProductListResp cardInfoResp = JsonUtil.parse(responseEntity.getBody(), GetProductListResp.class);
                if (cardInfoResp.getData() == null) {
                    return null;
                }
                List<Data> categorylist = cardInfoResp.getData();
                if (categorylist != null && categorylist.size() > 0) {
                    Condition categoryCondition = new Condition(ProductCategory.class);
                    categoryCondition.or().andEqualTo("shopid", shopId);
                    List<ProductCategory> productCategoryList =
                            productCategoryRepository.findByCondition(categoryCondition);

                    Map<String, Integer> productCategoryNameMap = null;
                    if (productCategoryList != null && productCategoryList.size() > 0) {
                        productCategoryNameMap =
                                productCategoryList.stream().collect(Collectors.toMap(ProductCategory::getName, ProductCategory::getId));
                    }

                    Condition productCondition = new Condition(Product.class);
                    productCondition.or().andEqualTo("shopid", shopId)
                            .andEqualTo("deleted", false)
                    ;

                    List<Product> productList = productRepository.findByCondition(productCondition);

                    Map<String, Product> dbProductList = null;
                    if (productList != null && productList.size() > 0) {
                        dbProductList =
                                productList.stream().collect(Collectors.toMap(Product::getSearchcode, pr -> pr));
                    }

                    Condition branchCondtion = new Condition(Branch.class);
                    branchCondtion.or().andEqualTo("shopId", shopId);
                    List<Branch> branchList = branchMapper.selectByCondition(branchCondtion);

                    Integer branchId;
                    if (branchList != null && branchList.size() > 0) {
                        branchId = branchList.get(0).getBranchId();
                    }else {
                        branchId = null;
                    }

                    List<String> shopRealProductIdList = new ArrayList<>();
                    for (Data data : categorylist) {
                        String categoryName = data.getCategoryname();

                        Integer categoryId = null;
                        if (productCategoryNameMap != null && productCategoryNameMap.containsKey(categoryName)) {
                            categoryId = productCategoryNameMap.get(categoryName);
                        }else {
                            ProductCategory productCategory = new ProductCategory();
                            productCategory.setDeleted(false);
                            productCategory.setName(categoryName);
                            productCategory.setParentid(0);
                            productCategory.setShopid(shopId);
                            productCategory.setType(new Byte("1"));
                            productCategoryRepository.save(productCategory);
                            categoryId = productCategory.getId();
                        }

                        List<Foodlist> foodlists = data.getFoodlist();

                        if (foodlists != null && foodlists.size() > 0) {
                            for (Foodlist foodlist : foodlists) {
                                shopRealProductIdList.add(foodlist.getFoodid());

                                if (dbProductList != null && dbProductList.containsKey(foodlist.getFoodid())) {
                                    Product dbProduct = dbProductList.get(foodlist.getFoodid());

                                    if (!dbProduct.getName().equals(foodlist.getFoodname())
                                            || new BigDecimal(dbProduct.getPrice()).divide(new BigDecimal(100)).doubleValue() != foodlist.getPrice()
                                            || dbProduct.getProductpic() == null
                                            || !dbProduct.getProductpic().equals(foodlist.getImage())
                                            ) {
                                        Product temp = new Product();
                                        temp.setId(dbProduct.getId());
                                        temp.setName(foodlist.getFoodname());
                                        long price = new Double(new Double(foodlist.getPrice()) * 100).longValue();
                                        temp.setPrice(price);
                                        temp.setProductpic(foodlist.getImage());
                                        temp.setMinorcategoryid(categoryId);
                                        temp.setSearchcode(foodlist.getFoodid());

                                        productMapper.updateByPrimaryKeySelective(temp);

                                        //图片变化时，删除已有图片
                                        if (dbProduct.getProductpic() == null || !dbProduct.getProductpic().equals(foodlist.getImage())) {
                                            delImg(dbProduct.getId(), branchId);

                                            //添加新图片
                                            addImg(dbProduct.getId(), foodlist.getImage(), branchId);

                                        }
                                    }
                                }else{//新菜品
                                    Product temp = new Product();
                                    temp.setName(foodlist.getFoodname());
                                    long price = new Double(new Double(foodlist.getPrice()) * 100).longValue();
                                    temp.setPrice(price);
                                    temp.setProductpic(foodlist.getImage());
                                    temp.setMinorcategoryid(categoryId);
                                    temp.setShopid(shopId);
                                    temp.setStoreid(branchId);
                                    temp.setVipprice(price);
                                    temp.setCreated(new Date());
                                    temp.setUpdated(temp.getCreated());
                                    temp.setSearchcode(foodlist.getFoodid());
                                    temp.setDeleted(false);
                                    temp.setStatus(new Byte("1"));
                                    productRepository.save(temp);
                                    addImg(temp.getId(), foodlist.getImage(), branchId);
                                }

                            }
                        }
                    }


                    for (Map.Entry<String, Product> entry : dbProductList.entrySet()) {
                        if (!entry.getKey().equals("-5")) {
                            if (!shopRealProductIdList.contains(entry.getKey())) {
                                Product tempProduct = entry.getValue();
                                delImg(tempProduct.getId(), branchId);

                                tempProduct.setDeleted(true);
                                productMapper.updateByPrimaryKeySelective(tempProduct);
                            }
                        }
                    }

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return null;
    }

    @Override
    public BaseChargeResp qrCodePay(OrderDTO orderDTO) {
        return null;
    }

    private static void getProductTemp(){
        TreeMap<String, String> param = new TreeMap();
        param.put("appid", appIdStatic);
        param.put("nonceStr", UUID.randomUUID().toString().replaceAll("-", ""));
        param.put("password", passwordStatic);
        param.put("branchid", branchIdStatic);
        param.put("time", simpleDateFormat.format(new Date()));

        String sign = param.get("appid") +
                param.get("password") + param.get("nonceStr") +
                param.get("time") + param.get("branchid");

        logger.info(sign);
        sign = MD5Util.MD5Lower32(sign);

        param.put("sign", sign);
        param.remove("password");

        String p = sitProductRequestUrl + "?";
        for (Map.Entry<String, String> entry : param.entrySet()) {
            p += entry.getKey() + "=" + entry.getValue() + "&";
        }


        p = p.substring(0, p.length() - 1);
        logger.info(p);

        ResponseEntity<String> responseEntity =
                new RestTemplate().getForEntity(p, String.class, new HashMap<>());

        logger.info(responseEntity.getBody());
    }

    private ConsumeResp doPay(OrderDTO orderDTO, String payType) {

        HttpHeaders DEFAULT_JSON_HEADER_UTF8 = new HttpHeaders();
        DEFAULT_JSON_HEADER_UTF8.setContentType(MediaType.APPLICATION_JSON_UTF8);
        ConsumeParam consumeParam = new ConsumeParam();

        if (orderDTO.getItems() != null && orderDTO.getItems().size() > 0) {
            List<ConsumeProduct> d = new ArrayList<>();
            for (OrderItemDTO orderItemDTO : orderDTO.getItems()) {
                ConsumeProduct p = new ConsumeProduct();
                Product product = DataLoadService.productMap.get(orderItemDTO.getProductId());
                if (product == null) {
                    product = productMapper.selectByPrimaryKey(orderItemDTO.getProductId());
                }

                if ("-5".equals(product.getSearchcode())) {
                    List<Product> productList = null;
                    if (DataLoadService.shopProductListMap != null) {
                        productList = DataLoadService.shopProductListMap.get(shopId);
                    }else {
                        Condition condition = new Condition(Product.class);
                        condition.or().andEqualTo("shopid", shopId)
                        .andEqualTo("deleted", false);
                        productList = productMapper.selectByCondition(condition);
                    }

                    for (Product temp : productList) {
                        if (temp.getPrice().intValue() == 1) {
                            p.setFoodId(temp.getSearchcode());
                            p.setQuantity(orderDTO.getRealFee().intValue());
                            p.setPrice(Double.valueOf(PriceUtil.changeF2Y(1l)));
                            break;
                        }
                    }
                }else {
                    p.setFoodId(product.getSearchcode());
                    p.setQuantity(orderItemDTO.getQuantity());
                    p.setPrice(Double.valueOf(PriceUtil.changeF2Y(orderItemDTO.getPrice())));
                }
                d.add(p);
            }
            consumeParam.setDetail(d);
        }
        consumeParam.setAppid(appIdStatic);
        consumeParam.setBranchid(branchIdStatic);
        consumeParam.setMoney(orderDTO.getRealFee());
        consumeParam.setNonceStr(UUID.randomUUID().toString().replaceAll("-", ""));
        consumeParam.setPayTime(simpleDateFormat.format(new Date()));
        consumeParam.setPayType(payType);
        if ("card".equals(payType)){
            consumeParam.setCardNo(orderDTO.getCardNo());
        }else {
            consumeParam.setCardNo("");
        }

        consumeParam.setTime(consumeParam.getPayTime());
        consumeParam.setTradeid(orderDTO.getOrderNo());

        String sign = consumeParam.getAppid() + consumeParam.getCardNo() +
                passwordStatic + consumeParam.getNonceStr()
                + consumeParam.getTime()
                + consumeParam.getBranchid()
                + consumeParam.getTradeid()
                + consumeParam.getPayType()
                + consumeParam.getMoney();

        //sign=MD5(appid+cardNo+password + nonceStr +time + branchid +tradeid+ payType+money)

        sign = MD5Util.MD5Lower32(sign);

        consumeParam.setSign(sign);

        try {
            String param = JsonUtil.toJson(consumeParam);
            logger.info("renshoutang request param: {}", param);
            HttpEntity entity = new HttpEntity<>(param, DEFAULT_JSON_HEADER_UTF8);

            logger.info(JsonUtil.toJson(consumeParam));

            ResponseEntity<String> responseEntity =
                    new RestTemplate().postForEntity(sitConsumeRequestUrl, entity, String.class);

            logger.info(responseEntity.getBody());
            ConsumeResp consumeResp = JsonUtil.parse(responseEntity.getBody(), ConsumeResp.class);

            logger.info("" + consumeResp.getData().getBalance());

            return consumeResp;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    private static String getSign(TreeMap<String, String> param) {

        String sign = param.get("appid") + param.get("cardNo") +
                param.get("password") + param.get("nonceStr") + param.get("time");

        sign = MD5Util.MD5Lower32(sign);

        return sign;
    }

    public void addImg(Integer productId, String imgUrl, Integer branchId){
        //添加新图片
//        ThreadManager.executorService.execute(() -> {
            try {

                String filepath = "/usr/local/nginx/html/images/source/" + shopId + "/" + productId;
                File file = new File(filepath);

                if (!file.exists()) {
                    file.mkdir();
                }

                String filename = filepath + "/" + UUID.randomUUID() + ".png";

                FileDownloader.downloadNet(imgUrl, filename);

                String cont_sign = baiduRecUtil.addImg(shopId, filename, shopId + "_" + productId, branchId);

                LogProductImg logProductImg = new LogProductImg();
                logProductImg.setCutImg(imgUrl);
                logProductImg.setProductId(productId);
                logProductImg.setShopId(shopId);
                logProductImg.setSourceImg(imgUrl);
                logProductImg.setContSign(cont_sign);
                logProductImg.setCreateTime(new Date());
                logProductImg.setBaiduDeleted(0);
                logProductImg.setFromWxUpload(1);
                logProductImg.setBranchId(branchId);

                logProductImgMapper.insert(logProductImg);


                Product product = new Product();
                product.setProductpic(imgUrl);
                product.setId(productId);
                productMapper.updateByPrimaryKeySelective(product);

            } catch (Exception e) {
                e.printStackTrace();
            }
//        });
    }

    public void delImg(Integer productId, Integer branchId){

        //删除微信上传图片
        Condition logProductImgCondtion = new Condition(LogProductImg.class);
        logProductImgCondtion.or().andEqualTo("shopId", shopId)
                .andEqualTo("productId", productId)
                .andEqualTo("baiduDeleted", 0)
        ;

        List<LogProductImg> logProductImgList = logProductImgMapper.selectByCondition(logProductImgCondtion);
        if (logProductImgList != null && logProductImgList.size() > 0) {
            ThreadManager.executorService.execute(() -> {
                for (LogProductImg logProductImg : logProductImgList) {
                    String contSign = logProductImg.getContSign();
                    if(!baiduRecUtil.delImg(contSign, shopId, branchId)){
                        LogShopBaiduImgDel logShopBaiduImgDel = new LogShopBaiduImgDel();
                        logShopBaiduImgDel.setLogId(logProductImg.getId());
                        logShopBaiduImgDel.setStatus(0);
                        logShopBaiduImgDel.setImgType(1);
                        logShopBaiduImgDelMapper.insertSelective(logShopBaiduImgDel);
                    }else{
                        LogProductImg temp = new LogProductImg();
                        temp.setId(logProductImg.getId());
                        temp.setBaiduDeleted(1);
                        logProductImgMapper.updateByPrimaryKeySelective(temp);
                    }
                }
            });
        }


        //删除纠正图片
        Condition logProductImgFromUserCondtion = new Condition(LogProductImgFromUser.class);
        logProductImgFromUserCondtion.or().andEqualTo("shopId", shopId)
                .andEqualTo("productId", productId)
                .andEqualTo("baiduDeleted", 0)
                .andEqualTo("subDb", 0)
        ;

        List<LogProductImgFromUser> logProductImgFromUserList = logProductImgFromUserMapper.selectByCondition(logProductImgFromUserCondtion);
        if (logProductImgFromUserList != null && logProductImgFromUserList.size() > 0) {
            ThreadManager.executorService.execute(() -> {
                for (LogProductImgFromUser logProductImgFromUser : logProductImgFromUserList) {
                    String contSign = logProductImgFromUser.getContSign();
                    if(!baiduRecUtil.delImg(contSign, shopId, branchId)){
                        LogShopBaiduImgDel logShopBaiduImgDel = new LogShopBaiduImgDel();
                        logShopBaiduImgDel.setImgType(2);
                        logShopBaiduImgDel.setLogId(logProductImgFromUser.getId());
                        logShopBaiduImgDel.setStatus(0);
                        logShopBaiduImgDelMapper.insertSelective(logShopBaiduImgDel);
                    }else{
                        LogProductImgFromUser temp = new LogProductImgFromUser();
                        temp.setId(logProductImgFromUser.getId());
                        temp.setBaiduDeleted(1);
                        logProductImgFromUserMapper.updateByPrimaryKeySelective(temp);
                    }
                }
            });
        }

        //删除小库纠正图片
        Condition logProductImgFromUserCondtionCur = new Condition(LogProductImgFromUser.class);
        logProductImgFromUserCondtionCur.or().andEqualTo("shopId", shopId)
                .andEqualTo("productId", productId)
                .andEqualTo("baiduDeleted", 0)
                .andEqualTo("subDb", 1)
        ;

        List<LogProductImgFromUser> logProductImgFromUserListCur = logProductImgFromUserMapper.selectByCondition(logProductImgFromUserCondtionCur);
        if (logProductImgFromUserListCur != null && logProductImgFromUserListCur.size() > 0) {
            ThreadManager.executorService.execute(() -> {
                for (LogProductImgFromUser logProductImgFromUser : logProductImgFromUserListCur) {
                    String contSign = logProductImgFromUser.getContSign();
                    if(!baiduRecUtil.delImgCurList(contSign, shopId, branchId, logProductImgFromUser.getBaiduAppId())){
                        LogShopBaiduImgDel logShopBaiduImgDel = new LogShopBaiduImgDel();
                        logShopBaiduImgDel.setImgType(2);
                        logShopBaiduImgDel.setLogId(logProductImgFromUser.getId());
                        logShopBaiduImgDel.setStatus(0);
                        logShopBaiduImgDelMapper.insertSelective(logShopBaiduImgDel);
                    }else{
                        LogProductImgFromUser temp = new LogProductImgFromUser();
                        temp.setId(logProductImgFromUser.getId());
                        temp.setBaiduDeleted(1);
                        logProductImgFromUserMapper.updateByPrimaryKeySelective(temp);
                    }
                }
            });
        }

        /*//删除小库纠正图片
        Condition logProductImgCurCondtion = new Condition(LogProductImgCur.class);
        logProductImgCurCondtion.or().andEqualTo("shopId", shopId)
                .andEqualTo("productId", productId)
                .andEqualTo("baiduDeleted", 0)
        ;

        List<LogProductImgCur> logProductImgCurList = logProductImgCurMapper.selectByCondition(logProductImgCurCondtion);
        if (logProductImgCurList != null && logProductImgCurList.size() > 0) {
            ThreadManager.executorService.execute(() -> {
                for (LogProductImgCur logProductImgCur : logProductImgCurList) {
                    String contSign = logProductImgCur.getContSign();
                    if(baiduRecUtil.delImgCur(contSign, shopId, branchId)){
                        LogProductImgCur temp = new LogProductImgCur();
                        temp.setId(logProductImgCur.getId());
                        temp.setBaiduDeleted(1);
                        logProductImgCurMapper.updateByPrimaryKeySelective(temp);
                    }
                }
            });
        }*/
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Condition condition = new Condition(Shop.class);
        condition.or().andEqualTo("apiServiceClassName", "RenShouTangService");
        List<Shop> shopList = shopMapper.selectByCondition(condition);

        if (shopList != null && shopList.size() > 0) {
            shopId = shopList.get(0).getId();
            shopName = shopList.get(0).getName();
        }

        File file = new File("/usr/local/nginx/html/images/source/" + shopId);

        if (!file.exists()) {
            file.mkdir();
        }

//        getProductList();
    }
}
